package com.ruoyi.system.V2.goodInfo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.Constant;
import com.ruoyi.common.enums.SalerStatus;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.system.V2.financial.mapper.FinanceMapper;
import com.ruoyi.system.V2.financial.service.IFinanceService;
import com.ruoyi.system.V2.gameAttr.mapper.AccountAttrValueMapper;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.gameAttr.service.IGameAttrTemplateService;
import com.ruoyi.system.V2.gameInfo.mapper.GameInfoMapper;
import com.ruoyi.system.V2.goodInfo.domain.ExportJYMGoods;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoMapper;
import com.ruoyi.system.V2.goodInfo.service.IGoodsInfoService;
import com.ruoyi.system.V2.inter.mapper.SalePartnerMapper;
import com.ruoyi.system.V2.operation.service.IOperationHistoryService;
import com.ruoyi.system.V2.phone.mapper.TelManageMapper;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodReq;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueReq;
import com.ruoyi.system.model.service.AsyncService;
import com.ruoyi.system.model.vo.DeleteAllVo;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.goods.AdapterApi;
import com.ruoyi.system.saleorder.domain.SaleGoodsAfter;
import com.ruoyi.system.saleorder.domain.SaleGoodsAfterReq;
import com.ruoyi.system.saleorder.service.ISaleGoodsAfterService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * goodsService业务层处理
 *
 * @author ruoyi
 * @date 2023-04-06
 */
@Service
public class GoodsInfoServiceImpl implements IGoodsInfoService {
    @Resource
    private GoodsInfoMapper goodsInfoMapper;
    @Resource
    private FinanceMapper financeMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Autowired
    private AdapterApi adapterApi;
    @Autowired
    private SalePartnerMapper salePartnerMapper;
    @Resource
    private AccountAttrValueMapper accountAttrValueMapper;

    @Autowired
    private IGameAttrTemplateService gameAttrTemplateService;

    @Resource
    private GameAttributeMapper gameAttributeMapper;

    @Resource
    private SysDictDataMapper sysDictDataMapper;

    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;

    @Autowired
    private IOperationHistoryService operationHistoryService;

    @Resource
    private TelManageMapper telManageMapper;

    @Autowired
    private AsyncService asyncService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IFinanceService financeService;

    @Autowired
    private GameInfoMapper gameInfoMapper;
    @Autowired
    private ISaleGoodsAfterService saleGoodsAfterService;

    /**
     * 查询goods
     *
     * @param id goods主键
     * @return goods
     */
    @Override
    public GoodsInfo selectGoodsInfoById(Long id) {
        return goodsInfoMapper.selectGoodsInfoById(id);
    }

    /**
     * 查询goods列表
     *
     * @param goodsInfo goods
     * @return goods
     */
    @Override
    public List<GoodsInfo> selectGoodsInfoList(GoodsInfo goodsInfo) {
        return goodsInfoMapper.selectGoodsInfoList(goodsInfo);
    }

    /**
     * 新增goods
     *
     * @param goodsInfo goods
     * @return 结果
     */
    @Override
    public int insertGoodsInfo(GoodsInfo goodsInfo) {
        goodsInfo.setCreateTime(DateUtils.getNowDate());
        return goodsInfoMapper.insertGoodsInfo(goodsInfo);
    }

    /**
     * 普通加价
     *
     * @param goodsInfos
     * @param sysUserList
     */
    @Override
    public void bacthAddPrice(List<GoodsInfo> goodsInfos, List<SysUser> sysUserList) {

        for (GoodsInfo goodsInfo : goodsInfos) {
            BigDecimal bigDecimal = addPrice(goodsInfo.getPrice(), goodsInfo.getCreateId(), sysUserList);
            goodsInfo.setNewPrice(bigDecimal);
            if (Objects.isNull(goodsInfo.getNewPrice())) {
                goodsInfo.setNewPrice(goodsInfo.getPrice());
            }
        }
    }


    public void bacthAccRetaiById(List<GoodsInfo> list, List<SysUser> supplyCustomer, Long id) {

        for (GoodsInfo goodsInfo : list) {
            if (Objects.equals(id, goodsInfo.getCreateId())) {
                goodsInfo.setNewPrice(goodsInfo.getPrice());
            } else {
                BigDecimal bigDecimal = addPrice(goodsInfo.getPrice(), goodsInfo.getCreateId(), supplyCustomer);
                goodsInfo.setNewPrice(bigDecimal);
            }
        }
    }

    public BigDecimal addPrice(BigDecimal price, Long createId, List<SysUser> supplyCustomer) {

        /**
         * 供货商价 * 折扣  == 给供货商的钱
         * 供货商价 * 0.05 == 利润
         * （利润 + 供货价的钱） / 0.9
         * 供货商价 * 0.1 = 利润
         * 供货价 *
         *
         */
        for (SysUser sysUser : supplyCustomer) {
            if (Objects.nonNull(sysUser) && Objects.equals(sysUser.getUserId(), createId)) {

                //给供货商的钱
                Integer discountt = sysUser.getDiscountt();
                BigDecimal zhekou = new BigDecimal(discountt).divide(new BigDecimal(100));
                BigDecimal multiply = price.multiply(zhekou);

                //利润
                BigDecimal bigDecimal1 = new BigDecimal(sysUser.getRise()).divide(new BigDecimal(100));
                BigDecimal lirun = price.multiply(bigDecimal1);

                //利润 + 供货价
                BigDecimal add = lirun.add(multiply);

                //供货价  / 0.9 = 售价
                BigDecimal bigDecimal = add.divide(new BigDecimal(0.9), 0, BigDecimal.ROUND_UP);
                return bigDecimal;
            }
        }
        return null;
    }


    /**
     * 修改goods
     *
     * @param goodsInfo goods
     * @return 结果
     */
    @Override
    public int updateGoodsInfo(GoodsInfo goodsInfo) {
        goodsInfo.setUpdateTime(DateUtils.getNowDate());
        GoodsInfo info = goodsInfoMapper.selectGoodsInfoById(goodsInfo.getId());
        if (Objects.equals(info.getSaleState(), 1)) {
            GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto = new GoodsInfoAndAttrValueDto();
            BeanUtils.copyBeanProp(goodsInfoAndAttrValueDto, goodsInfo);
            excuTaskPoolEdit(goodsInfoAndAttrValueDto);
        }
        return goodsInfoMapper.updateGoodsInfo(goodsInfo);
    }

    /**
     * 批量删除goods
     *
     * @param ids 需要删除的goods主键
     * @return 结果
     */
    @Override
    public int deleteGoodsInfoByIds(Long[] ids) {

//        Arrays.asList(ids).stream().forEach(id -> {
//            GoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoById(id);
//            asyncService.excuTaskPool(id, null, Constant.del, goodsInfo.getCreateId(), 1l);
//        });
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        GoodsInfo goodsInfo = new GoodsInfo();
        goodsInfo.setIds(Arrays.asList(ids));
        goodsInfo.setDelUserId(sysUser.getUserId());
        goodsInfo.setDelUserName(sysUser.getNickName());

        return goodsInfoMapper.deleteGoodsInfoByIds(goodsInfo);
    }

    /**
     * 删除goods信息
     *
     * @param id goods主键
     * @return 结果
     */
    @Override
    public int deleteGoodsInfoById(Long id) {
        ArrayList<Long> ids = new ArrayList<>();
        ids.add(id);
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        GoodsInfo goodsInfo = new GoodsInfo();
        goodsInfo.setIds(ids);
        goodsInfo.setDelUserId(sysUser.getUserId());
        goodsInfo.setDelUserName(sysUser.getNickName());
        return goodsInfoMapper.deleteGoodsInfoByIds(goodsInfo);
    }

    @Override
    public GoodsInfoAndAttrValueDto selectGoodsInfoAndAttrValueById(Long id) {
        GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto = goodsInfoMapper.selectGoodsInfoAndAttrValueById(id);
        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType("1");
        List<GoodsInfoImg> goodsInfoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        List<Map<String, Object>> imgMaps = new ArrayList<>();
        for (GoodsInfoImg goodsImg : goodsInfoImgs) {
            Map<String, Object> imgMap = new HashMap<>();
            if (!StringUtils.isNull(goodsImg.getFileName()) && !StringUtils.isNull(goodsImg.getImgUrl())) {
                imgMap.put("name", goodsImg.getFileName());
                imgMap.put("url", goodsImg.getImgUrl());
                imgMaps.add(imgMap);
            }
        }
        if (!org.springframework.util.CollectionUtils.isEmpty(imgMaps)) {
            goodsInfoAndAttrValueDto.setUrlArr(imgMaps);
        }
        goodsInfoImg.setType("2");
        List<GoodsInfoImg> video = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        if (!org.springframework.util.CollectionUtils.isEmpty(video) && video.size() > 0) {
            goodsInfoAndAttrValueDto.setVideoName(video.get(0).getFileName());
            goodsInfoAndAttrValueDto.setVideoUrl(video.get(0).getImgUrl());
        }
        Finance finance = new Finance();
        finance.setField4(String.valueOf(goodsInfoAndAttrValueDto.getId()));
        List<Finance> finances = financeService.selectFinanceList(finance);
        if (CollectionUtils.isNotEmpty(finances)) {
            Finance finance1 = finances.get(0);
            goodsInfoAndAttrValueDto.setField1(finance1.getField1());
            goodsInfoAndAttrValueDto.setField2(finance1.getField2());
            goodsInfoAndAttrValueDto.setField3(finance1.getField3());
            goodsInfoAndAttrValueDto.setField4(finance1.getField4());
            goodsInfoAndAttrValueDto.setField5(finance1.getField5());
            goodsInfoAndAttrValueDto.setField6(finance1.getField6());
            goodsInfoAndAttrValueDto.setField7(finance1.getField7());
            goodsInfoAndAttrValueDto.setField8(finance1.getField8());
            if (Objects.isNull(finance1.getPrice())) {
                goodsInfoAndAttrValueDto.setZdPrice("0");
            } else {
                goodsInfoAndAttrValueDto.setZdPrice(finance1.getPrice().toPlainString());
            }
            goodsInfoAndAttrValueDto.setZdRemark(finance1.getRemark());
            goodsInfoAndAttrValueDto.setAtta(finance1.getAtta());
        }
        return goodsInfoAndAttrValueDto;
    }

    @Override
    @Transactional
    public int insertGoodsInfoAndAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto) {
        GoodsInfo goodsInfo = new GoodsInfo();
        AccountAttrValue accountAttrValue = new AccountAttrValue();
        BeanUtils.copyBeanProp(goodsInfo, goodsInfoAndAttrValueDto);
        BeanUtils.copyBeanProp(accountAttrValue, goodsInfoAndAttrValueDto);
        String allFeild = getAllField(goodsInfo, accountAttrValue);
        goodsInfo.setAllField(allFeild);
        goodsInfo.setCreateId(SecurityUtils.getUserId());
        int count = insertGoodsInfo(goodsInfo);
        if (Objects.nonNull(goodsInfo.getTelid())) {
            GameInfo gameInfo = gameInfoMapper.selectGameInfoById(goodsInfo.getGameId());
            if (Objects.equals(gameInfo.getGameType(), "网易")) {
                TelManage telManage = telManageMapper.selectTelManageById(goodsInfo.getTelid());
                if (StringUtils.equals(telManage.getWyStatus(), "1")) {
                    TelManage manage = new TelManage();
                    manage.setId(goodsInfo.getTelid());
                    manage.setWyStatus("3");
                    telManageMapper.updateTelManage(manage);
                } else {
                    throw new GlobalException("网易帐号绑定中");
                }
            }
        }
        goodsInfoAndAttrValueDto.setId(goodsInfo.getId());
        if (!CollectionUtils.isEmpty(goodsInfoAndAttrValueDto.getUrlArr())) {
            bathAddImg(goodsInfoAndAttrValueDto.getUrlArr(), goodsInfo.getId());
        }
        if (!StringUtils.isNull(goodsInfoAndAttrValueDto.getVideoUrl())) {
            addVideo(goodsInfoAndAttrValueDto.getVideoUrl(), goodsInfoAndAttrValueDto.getVideoName(),
                    goodsInfo.getId());
        }
        accountAttrValue.setAccountInfoId(goodsInfo.getId());
        //保存自定义字段
        accountAttrValueMapper.insertAccountAttrValue(accountAttrValue);
        //设置手机号
        setPhone(goodsInfoAndAttrValueDto);
        //异步推送接口
        excuTaskPoolAdd(goodsInfoAndAttrValueDto);
        pushFinance(goodsInfoAndAttrValueDto);
        return count;
    }


    private void excuTaskPoolAdd(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto) {

        String salepartnerids = goodsInfoAndAttrValueDto.getSalepartnerids();
        if (StringUtils.isNotEmpty(salepartnerids)) {
            String[] split = salepartnerids.split(",");
            for (String s : split) {
                asyncService.excuAddTask(goodsInfoAndAttrValueDto, Long.parseLong(s));
            }
        }

    }

    private void excuTaskPoolEdit(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto) {
        System.out.println("2222222222222222222222222222222222222222222222222222222222222");
//        String salepartnerids = goodsInfoAndAttrValueDto.getSalepartnerids();
        asyncService.excuTaskPool(goodsInfoAndAttrValueDto.getId(), null, Constant.edit,
                goodsInfoAndAttrValueDto.getCreateId(), 1l);
//        if (StringUtils.isNotEmpty(salepartnerids)) {
//            String[] split = salepartnerids.split(",");
//            for (String s : split) {
//
//            }
//        }

    }


    @Override
    @Transactional
    public int updateGoodsInfoAndAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto) {
        GoodsInfo goodsInfo = new GoodsInfo();
        AccountAttrValue accountAttrValue =
                accountAttrValueMapper.selectAccountAttrValueByAccountInfoId(goodsInfoAndAttrValueDto.getId());
        if (accountAttrValue != null) {
            Long aavId = accountAttrValue.getId();
            BeanUtils.copyBeanProp(goodsInfo, goodsInfoAndAttrValueDto);
            BeanUtils.copyBeanProp(accountAttrValue, goodsInfoAndAttrValueDto);
            String allFeild = getAllField(goodsInfo, accountAttrValue);
            goodsInfo.setAllField(allFeild);
            goodsInfo.setUpdateId(SecurityUtils.getUserId());
            updateGoodsInfo(goodsInfo);
            if (!CollectionUtils.isEmpty(goodsInfoAndAttrValueDto.getUrlArr())) {
                bathAddImg(goodsInfoAndAttrValueDto.getUrlArr(), goodsInfo.getId());
            } else {
                goodsInfoImgMapper.deleteByGoodsId(goodsInfo.getId(), Constants.STR_1);
            }
            if (!StringUtils.isNull(goodsInfoAndAttrValueDto.getVideoUrl())) {
                addVideo(goodsInfoAndAttrValueDto.getVideoUrl(), goodsInfoAndAttrValueDto.getVideoName(),
                        goodsInfoAndAttrValueDto.getId());
            }
            accountAttrValue.setId(aavId);
            //添加到任务池
            excuTaskPoolEdit(goodsInfoAndAttrValueDto);
            accountAttrValueMapper.updateAccountAttrValue(accountAttrValue);

//            //螃蟹改价
//            SalePartner salePartner = salePartnerMapper.selectSalePartnerById(7l);
//            adapterApi.editGame(goodsInfoAndAttrValueDto,salePartner);

            System.out.println("111111111111111111111111111111111111111111111111111111111111111111");
        } else {
            throw new GlobalException("找不到此商品属性信息");
        }
        setPhone(goodsInfoAndAttrValueDto);
        recOperHistory(goodsInfoAndAttrValueDto);
        if (Objects.nonNull(goodsInfoAndAttrValueDto.getTelid()) && !Objects.equals(goodsInfoAndAttrValueDto.getTelid(), goodsInfo.getTelid())) {
            GameInfo gameInfo = gameInfoMapper.selectGameInfoById(goodsInfo.getGameId());
            if (Objects.equals(gameInfo.getGameType(), "网易")) {
                TelManage telManage = telManageMapper.selectTelManageById(goodsInfo.getTelid());
                if (StringUtils.equals(telManage.getWyStatus(), "1")) {
                    TelManage manage = new TelManage();
                    manage.setId(goodsInfo.getTelid());
                    manage.setWyStatus("3");
                    telManageMapper.updateTelManage(manage);
                } else {
                    throw new GlobalException("网易帐号绑定中");
                }
            }
        }
        return 1;
    }

    private void setPhone(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto) {
        //校验是否有telid
        //查询手机管理
        Long telid = goodsInfoAndAttrValueDto.getTelid();
        if (Objects.isNull(telid)) {
            TelManage telManage = new TelManage();
            telManage.setTel(goodsInfoAndAttrValueDto.getSecurityPhone());
            List<TelManage> telManages = telManageMapper.selectTelManageList(telManage);
            if (CollectionUtils.isNotEmpty(telManages)) {
                goodsInfoAndAttrValueDto.setTelid(telManages.get(0).getId());
            }
        }
    }

    private void recOperHistory(GoodsInfoAndAttrValueDto goodsInfo) {
        if (null != goodsInfo.getId()) {
            GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto =
                    goodsInfoMapper.selectGoodsInfoAndAttrValueById(goodsInfo.getId());
            String newString = JSONObject.toJSONString(goodsInfoAndAttrValueDto);
            String oldstring = JSONObject.toJSONString(goodsInfo);
            LoginUser loginUser = SecurityUtils.getLoginUser();
            OperationHistory operationHistory = new OperationHistory();
            operationHistory.setAccountId(goodsInfo.getId());
            operationHistory.setOperator(loginUser.getUsername());
            operationHistory.setOperatTime(new Date());
            operationHistory.setStatus("编辑");
            operationHistory.setReason(oldstring + "->" + newString);
            operationHistoryService.insertOperationHistory(operationHistory);
        }
    }

    @Override
    public List<GoodsInfoAndAttrValueDto> selectGoodsInfoAndAttrList(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto) {
        Field[] fields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();
        Map map1 = new HashMap();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                if (field.getName().startsWith("f")) {
                    map1.put(field.getName(), field.get(goodsInfoAndAttrValueDto));
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        GameAttrTemplate gameAttrTemplateCX = new GameAttrTemplate();
        gameAttrTemplateCX.setGameId(goodsInfoAndAttrValueDto.getGameId());
        List<GameAttrTemplate> gameAttrTemplates =
                gameAttrTemplateService.selectGameAttrTemplateList(gameAttrTemplateCX);
        StringBuffer sbuffer = new StringBuffer();
        if (CollectionUtils.isNotEmpty(gameAttrTemplates)) {
            for (GameAttrTemplate gameAttrTemplate : gameAttrTemplates) {
                Object aa = map1.get(gameAttrTemplate.getAavName());
                pinjie(aa, gameAttrTemplate, sbuffer);
            }
            goodsInfoAndAttrValueDto.setRemark(sbuffer.toString());
            System.out.println("sbuffer=" + goodsInfoAndAttrValueDto.getRemark());
        }
        List<GoodsInfoAndAttrValueDto> goodsInfoAndAttrValueDtos =
                goodsInfoMapper.selectGoodsInfoAndAttrList(goodsInfoAndAttrValueDto);
        System.out.println("goodsInfoAndAttrValueDtos的size：" + goodsInfoAndAttrValueDtos.size());
        return goodsInfoAndAttrValueDtos;
    }

    @Override
    @Transactional
    public int upGoodsById(Long id) {
        GoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoById(id);
        if (Objects.isNull(goodsInfo)) {
            throw new GlobalException("未找到此商品");
        }
        goodsInfo.setSaleState(0);

        Map<String, Object> params = new HashMap<>();
        params.put("operation", "上架");
        setOper(id, params);
        return goodsInfoMapper.updateGoodsInfo(goodsInfo);
    }

    public int upGoodsById(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto) {
        GoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoById(goodsInfoAndAttrValueDto.getId());
        if (Objects.isNull(goodsInfo)) {
            throw new GlobalException("未找到此商品");
        }
        goodsInfo.setSaleState(0);
        goodsInfo.setProblemDes(goodsInfoAndAttrValueDto.getProblemDes());
        Map<String, Object> params = new HashMap<>();
        params.put("operation", "上架");
        setOper(goodsInfoAndAttrValueDto.getId(), params);

        SaleGoodsAfterReq after = new SaleGoodsAfterReq();
        after.setGoodsId(goodsInfoAndAttrValueDto.getId());
        List<SaleGoodsAfter> afters = saleGoodsAfterService.selectSaleGoodsAfterList(after);
        if (CollectionUtils.isNotEmpty(afters)) {
            for (SaleGoodsAfter saleGoodsAfter : afters) {
                saleGoodsAfterService.deleteSaleGoodsAfterById(saleGoodsAfter.getId());
            }
        }
        return goodsInfoMapper.updateGoodsInfo(goodsInfo);
    }

    @Override
    @Transactional
    public int downGoodsById(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto) {
        GoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoById(goodsInfoAndAttrValueDto.getId());
        if (Objects.isNull(goodsInfo)) {
            throw new GlobalException("未找到此商品");
        }
        if (StringUtils.isEmpty(goodsInfoAndAttrValueDto.getDownDes())) {
            throw new GlobalException("请填写下架备注");
        }
        goodsInfo.setDownDes(goodsInfoAndAttrValueDto.getDownDes());
        goodsInfo.setSaleState(4);

        Map<String, Object> params = new HashMap<>();
        params.put("operation", "下架");
        setOper(goodsInfoAndAttrValueDto.getId(), params);
//        asyncService.excuTaskPool(goodsInfoAndAttrValueDto.getId(), null, Constant.del, goodsInfo.getCreateId(), 1l);
//        //螃蟹下架
//        try {
//            //螃蟹下架
//            SalePartner salePartner = salePartnerMapper.selectSalePartnerById(7l);
//            adapterApi.delGame(goodsInfoAndAttrValueDto, salePartner);
//        }catch (Exception e){
//        }
        return goodsInfoMapper.updateGoodsInfo(goodsInfo);
    }

    @Override
    @Transactional
    public int problemGoods(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto) {
        Integer taskType = null;
        GoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoById(goodsInfoAndAttrValueDto.getId());
        if (goodsInfo.getSaleState() != null) {
            if (goodsInfo.getSaleState() == 1 || goodsInfo.getSaleState() == 2) {
                taskType = 1;
            } else if (goodsInfo.getSaleState() == 3) {
                taskType = 2;
            }
        }
        if (Objects.isNull(goodsInfo)) {
            throw new GlobalException("未找到此商品");
        }
        if (StringUtils.isEmpty(goodsInfoAndAttrValueDto.getProblemDes())) {
            throw new GlobalException("请填写问题备注");
        }
        goodsInfo.setProblemDes(goodsInfoAndAttrValueDto.getProblemDes());
        goodsInfo.setProblemTypeName(goodsInfoAndAttrValueDto.getProblemTypeName());
        goodsInfo.setSaleState(5);

        Map<String, Object> params = new HashMap<>();
        params.put("operation", "转问题");
        setOper(goodsInfoAndAttrValueDto.getId(), params);
//        asyncService.excuTaskPool(goodsInfoAndAttrValueDto.getId(), null, Constant.del, goodsInfo.getCreateId(), 1l);
//        try {
//            //螃蟹下架
//            SalePartner salePartner = salePartnerMapper.selectSalePartnerById(7l);
//            adapterApi.delGame(goodsInfoAndAttrValueDto, salePartner);
//        }catch (Exception e){
//        }
        goodsInfo.setProblemtime(new Date());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        goodsInfo.setProblemUserId(loginUser.getUserId());
        goodsInfo.setProblemUserName(loginUser.getUser().getNickName());

        // 同步售后处理
        saleGoodsAfterService.pushAfter(goodsInfo, taskType, SecurityUtils.getUserId());
        return goodsInfoMapper.updateGoodsInfo(goodsInfo);
    }

    @Override
    @Transactional
    public int retrieveGoods(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto) {
        GoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoById(goodsInfoAndAttrValueDto.getId());
        if (Objects.isNull(goodsInfo)) {
            throw new GlobalException("未找到此商品");
        }
        if (StringUtils.isEmpty(goodsInfoAndAttrValueDto.getRetrieveDes())) {
            throw new GlobalException("请填写找回备注");
        }
        goodsInfo.setRetrieveDes(goodsInfoAndAttrValueDto.getRetrieveDes());
        goodsInfo.setRetrieveHandleType(goodsInfoAndAttrValueDto.getRetrieveHandleType());
        goodsInfo.setRetrieveHandleImages(goodsInfoAndAttrValueDto.getRetrieveHandleImages());

        goodsInfo.setSaleState(6);

        LoginUser loginUser = SecurityUtils.getLoginUser();
        goodsInfo.setRetrieveUserId(loginUser.getUserId());
        goodsInfo.setRetrieveUserName(loginUser.getUser().getNickName());

        Map<String, Object> params = new HashMap<>();
        params.put("operation", "转找回");
        setOper(goodsInfoAndAttrValueDto.getId(), params);
        pushFinanceSH(goodsInfoAndAttrValueDto, goodsInfo);

        SaleGoodsAfterReq after = new SaleGoodsAfterReq();
        after.setGoodsId(goodsInfoAndAttrValueDto.getId());
        after.setAfterStatus(2);
        List<SaleGoodsAfter> afters = saleGoodsAfterService.selectSaleGoodsAfterList(after);
        if (CollectionUtils.isNotEmpty(afters)) {
            for (SaleGoodsAfter saleGoodsAfter : afters) {
                saleGoodsAfter.setAfterStatus(3);
                saleGoodsAfter.setOverTime(new Date());
                saleGoodsAfter.setOverId(SecurityUtils.getUserId());
                saleGoodsAfter.setOverName(SecurityUtils.getUsername());
                saleGoodsAfterService.updateSaleGoodsAfter(saleGoodsAfter);
            }
        }
        return goodsInfoMapper.updateGoodsInfo(goodsInfo);
    }

    public List<ExportJYMGoods> selectExportJYM(GoodsInfo goodsInfo) {
        List<ExportJYMGoods> result = new ArrayList<>();

        List<ExportJYMGoods> exportJYMGoods = goodsInfoMapper.selectExportJYM(goodsInfo);
        if (CollectionUtils.isNotEmpty(exportJYMGoods)) {
            List<SysDictData> sysDictDataList = sysDictDataMapper.selectDictDataByType("jym_export_config");
            String out1 = "";
            String out2 = "";
            String out3 = "";
            String out4 = "";
            String out5 = "";
            for (SysDictData dictData : sysDictDataList) {
                if ("out1".equals(dictData.getDictLabel())) {
                    out1 = dictData.getDictValue();
                }
                if ("out2".equals(dictData.getDictLabel())) {
                    out2 = dictData.getDictValue();
                }
                if ("out3".equals(dictData.getDictLabel())) {
                    out3 = dictData.getDictValue();
                }
                if ("out4".equals(dictData.getDictLabel())) {
                    out4 = dictData.getDictValue();
                }
                if ("out5".equals(dictData.getDictLabel())) {
                    out5 = dictData.getDictValue();
                }
            }

            Map<String, List<ExportJYMGoods>> collect = exportJYMGoods.stream().collect(Collectors.groupingBy(s -> s.getGoodsId()));
            ExportJYMGoods goods = new ExportJYMGoods();
            for (String goodsId : collect.keySet()) {
                List<ExportJYMGoods> exportJYMGoods1 = collect.get(goodsId);
                goods = exportJYMGoods1.get(0);
                for (ExportJYMGoods jymGoods : exportJYMGoods1) {
                    if (StringUtils.equals(jymGoods.getSaleCode(), out1)) {
                        goods.setOut1(jymGoods.getOutId());
                    }
                    if (StringUtils.equals(jymGoods.getSaleCode(), out2)) {
                        goods.setOut2(jymGoods.getOutId());
                    }
                    if (StringUtils.equals(jymGoods.getSaleCode(), out3)) {
                        goods.setOut3(jymGoods.getOutId());
                    }
                    if (StringUtils.equals(jymGoods.getSaleCode(), out4)) {
                        goods.setOut4(jymGoods.getOutId());
                    }
                    if (StringUtils.equals(jymGoods.getSaleCode(), out5)) {
                        goods.setOut5(jymGoods.getOutId());
                    }
                }
                result.add(goods);
            }
        }
        return result;
    }

    @Override
    public List<GoodsInfo> selectByResList(GoodsInfoAndAttrValueReq goodsInfoAndAttrValueReq, PageDomain pageDomain) {
        Field[] fields = goodsInfoAndAttrValueReq.getClass().getDeclaredFields();
        Map map1 = new HashMap();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                if (field.getName().startsWith("f")) {
                    map1.put(field.getName(), field.get(goodsInfoAndAttrValueReq));
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
//        GameAttrTemplate gameAttrTemplateCX = new GameAttrTemplate();
//        gameAttrTemplateCX.setGameId();
//        List<GameAttrTemplate> gameAttrTemplates =
//                gameAttrTemplateService.selectGameAttrTemplateList(gameAttrTemplateCX);
        List<GameAttrTemplate> gameAttrTemplates =
                gameAttrTemplateService.selectGameAttrTemplateByGameId(goodsInfoAndAttrValueReq.getGameId());
        StringBuffer sbuffer = new StringBuffer();
        if (CollectionUtils.isNotEmpty(gameAttrTemplates)) {
            for (GameAttrTemplate gameAttrTemplate : gameAttrTemplates) {
                Object aa = map1.get(gameAttrTemplate.getAavName());
                pinjie(aa, gameAttrTemplate, sbuffer);
            }
            List list = goodsInfoAndAttrValueReq.getBoxRadioValues();
            if (CollectionUtils.isNotEmpty(list)) {
                for (Object o : list) {
                    String value = o.toString();
                    if (StringUtils.contains(value, "===")) {
                        String[] vlas = value.split("===");
                        for (int i = 0; i < vlas.length; i++) {
                            if (i == 0) {
                                sbuffer.append("and ( all_field like \'%" + vlas[i] + "%\'");
                            } else {
                                if (i == vlas.length - 1) {
                                    sbuffer.append("or all_field like \'%" + vlas[i] + "%\' )");
                                } else {
                                    sbuffer.append("or all_field like \'%" + vlas[i] + "%\'");
                                }
                            }
                        }
                    } else {
                        sbuffer.append(" and all_field like \'%" + value + "%\'");
                    }
                }
            }
            goodsInfoAndAttrValueReq.setRemark(sbuffer.toString());
        }
        if (StringUtils.isNotEmpty(goodsInfoAndAttrValueReq.getSort())) {
            goodsInfoAndAttrValueReq.setSort(goodsInfoAndAttrValueReq.getSort().replace("ending", ""));
        }
        if (!StringUtils.isNull(goodsInfoAndAttrValueReq.getSortColumn())) {
            goodsInfoAndAttrValueReq.setSortColumn(humpToLine(goodsInfoAndAttrValueReq.getSortColumn()));
        }
        String[] keyWordArr = {};
        if (!StringUtils.isNull(goodsInfoAndAttrValueReq.getKeyWord())) {
            keyWordArr = goodsInfoAndAttrValueReq.getKeyWord().split(" ");
            goodsInfoAndAttrValueReq.setKeyWordArr(Arrays.asList(keyWordArr));
        }
        if (Objects.equals(Constants.ONE, goodsInfoAndAttrValueReq.getDataType())) {
            goodsInfoAndAttrValueReq.setCreateId(SecurityUtils.getUserId());
        }
        //分页
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            Boolean reasonable = pageDomain.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        List<GoodsInfo> goodsInfos = goodsInfoMapper.selectByResList(goodsInfoAndAttrValueReq);
        for (GoodsInfo goodsInfo : goodsInfos) {
            String monitoringState = goodsInfo.getMonitoringState();
            if (Objects.equals("3", monitoringState)) {
                goodsInfo.setMonitoringState("待检测");
            }
            if (Objects.equals("2", monitoringState)) {
                goodsInfo.setMonitoringState("已掉绑");
            }
            if (Objects.equals("1", monitoringState)) {
                goodsInfo.setMonitoringState("在绑");
            }
        }
        List<SysUser> supplyCustomer = userService.getUserByRoleCode("supplyCustomer");
        bacthAddPrice(goodsInfos, supplyCustomer);
        return goodsInfos;
    }

    /**
     * 批量审核
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public int auditGoods(Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        params.put("operation", "批量审核");
        for (Long id : ids) {
            setOper(id, params);
        }

        return goodsInfoMapper.auditGoods(ids);
    }

    @Override
    @Transactional
    public int submitAccount(Long[] ids) {

        Map<String, Object> params = new HashMap<>();
        params.put("operation", "提号");
        for (Long id : ids) {
            setOper(id, params);
        }


        return goodsInfoMapper.submitAccount(ids);
    }

    @Override
    public List<Map<String, Object>> countForSupply(GoodsInfo goodsInfo) {
        List<Map<String, Object>> list = goodsInfoMapper.countForSupply(goodsInfo.getCreateId());
        return list;
    }

    @Override
    public List<Map<String, Object>> userGameCount() {
        return goodsInfoMapper.userGameCount();
    }

    @Override
    public int down(Long[] ids) {

//        Arrays.asList(ids).stream().forEach(id -> {
//            GoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoById(id);
//            asyncService.excuTaskPool(id, null, Constant.del, goodsInfo.getCreateId(), 1l);
//        });


        return goodsInfoMapper.down(ids);
    }

    @Override
    public int toSaled(Long id) {

        GoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoById(id);
        if (Objects.nonNull(goodsInfo)) {
            goodsInfo.setSaleState(3);
            Map<String, Object> params = new HashMap<>();
            params.put("operation", "转为已售");
            setOper(id, params);
            if (Objects.nonNull(goodsInfo.getTelid())) {
                TelManage telManage = telManageMapper.selectTelManageByGoodsId(goodsInfo.getId());
                if (Objects.nonNull(telManage)) {
                    telManage.setWyStatus("4");
                    telManageMapper.updateTelManage(telManage);
                }
            }
            SaleGoodsAfterReq after = new SaleGoodsAfterReq();
            after.setGoodsId(id);
            List<SaleGoodsAfter> afters = saleGoodsAfterService.selectSaleGoodsAfterList(after);
            if (CollectionUtils.isNotEmpty(afters)) {
                for (SaleGoodsAfter saleGoodsAfter : afters) {
                    saleGoodsAfterService.deleteSaleGoodsAfterById(saleGoodsAfter.getId());
                }
            }
            return goodsInfoMapper.updateGoodsInfo(goodsInfo);
        } else {
            throw new GlobalException("没找到账号");
        }
    }

    @Override
    public int resetUnbindById(Long id) {
        GoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoById(id);
        if (Objects.nonNull(goodsInfo)) {
            goodsInfo.setMonitoringState("3");
            Map<String, Object> params = new HashMap<>();
            params.put("operation", "重置掉绑状态");
            setOper(id, params);
            return goodsInfoMapper.updateGoodsInfo(goodsInfo);
        } else {
            throw new GlobalException("没找到账号");
        }
    }

    @Override
    public int toTop(Long id) {


        GoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoById(id);
        if (Objects.nonNull(goodsInfo)) {
            goodsInfo.setCreateTime(new Date());
            Map<String, Object> params = new HashMap<>();
            params.put("operation", "置顶");
            setOper(id, params);
            return goodsInfoMapper.updateGoodsInfo(goodsInfo);
        } else {
            throw new GlobalException("没找到账号");
        }
    }


    @Override
    @Transactional
    public int submitAccount(JSONObject jsonObject) {

        Long id = jsonObject.getLong("id");
        if (Objects.isNull(id)) {
            throw new GlobalException("id 不允许为空");
        }

        String remake = jsonObject.getString("remake");

        Map<String, Object> params = new HashMap<>();
        params.put("operation", "提号");
        setOper(id, params);

        Date submittime = new Date();

        Long userId = SecurityUtils.getUserId();

        GoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoById(id);
        if (Objects.isNull(goodsInfo)) {
            throw new GlobalException("商品查询为空");
        }
        goodsInfo.setSubmittime(submittime);
        goodsInfo.setSubmituserid(userId);
        goodsInfo.setSalenote(remake);
        goodsInfo.setSaleState(2);

        return goodsInfoMapper.updateGoodsInfo(goodsInfo);
    }

    @Override
    @Transactional
    public int updateRemake(JSONObject jsonObject) {

        Long id = jsonObject.getLong("id");
        if (Objects.isNull(id)) {
            throw new GlobalException("id 不允许为空");
        }

        String remake = jsonObject.getString("remake");

        Map<String, Object> params = new HashMap<>();
        params.put("operation", "修改交易备注");
        setOper(id, params);


        GoodsInfo goodsInfo = goodsInfoMapper.selectGoodsInfoById(id);
        if (Objects.isNull(goodsInfo)) {
            throw new GlobalException("商品查询为空");
        }
        goodsInfo.setSalenote(remake);

        return goodsInfoMapper.updateGoodsInfo(goodsInfo);
    }

    @Override
    public int deleteAllAccount(DeleteAllVo deleteAllVo) {

        //供货人
        //配置
        List<String> supplyIdAddr = deleteAllVo.getSupplyIdAddr();
        if (CollectionUtils.isEmpty(supplyIdAddr)) {
            throw new GlobalException("请选择供货商");
        }
        List<Long> configArr = deleteAllVo.getConfigArr();

        if (!org.springframework.util.CollectionUtils.isEmpty(supplyIdAddr)) {
            GoodsInfo goodsInfo = new GoodsInfo();
            goodsInfo.setCreateIds(supplyIdAddr);
            goodsInfo.setSaleState(SalerStatus.unsold.getCode());
            List<GoodsInfo> goodsInfos = goodsInfoMapper.selectGoodsInfoList(goodsInfo);
            if (!org.springframework.util.CollectionUtils.isEmpty(goodsInfos)) {
                Long userId = goodsInfo.getCreateId();
                for (GoodsInfo info : goodsInfos) {
//                    if (!org.springframework.util.CollectionUtils.isEmpty(configArr)) {
//                        configArr.stream().forEach(a -> {
//                            asyncService.excuTaskPool(info.getId(), a, Constant.del, info.getCreateId(), userId);
//                        });
//                    } else {
//                        asyncService.excuTaskPool(info.getId(), null, Constant.del, info.getCreateId(), userId);
//                    }
                    info.setSaleState(4);
                    goodsInfoMapper.updateGoodsInfo(info);
                }
            }
        }
        return 1;
    }


    /**
     * 分销加价
     *
     * @param list
     * @param supplyCustomer
     */
    @Override
    public void bacthAccRetail(List<GoodsInfo> list, List<SysUser> supplyCustomer, Long userId) {

        for (GoodsInfo accountInfo : list) {
            if (Objects.equals(userId, accountInfo.getCreateId())) {
                accountInfo.setNewPrice(accountInfo.getPrice());
            } else {
                BigDecimal bigDecimal = addPrice(accountInfo.getPrice(), accountInfo.getCreateId(), supplyCustomer);
                accountInfo.setNewPrice(bigDecimal);
            }
            if (Objects.isNull(accountInfo.getCreateId())) {
                accountInfo.setNewPrice(accountInfo.getPrice());
            }
        }
    }

    /**
     * 分销加价
     *
     * @param list
     * @param supplyCustomer
     */
    @Override
    public void bacthAccRetailByUserId(List<GoodsInfo> list, List<SysUser> supplyCustomer, Long userId) {

        for (GoodsInfo accountInfo : list) {
            if (Objects.equals(userId, accountInfo.getCreateId())) {
                accountInfo.setNewPrice(accountInfo.getPrice());
            } else {
                BigDecimal bigDecimal = addPrice(accountInfo.getPrice(), accountInfo.getCreateId(), supplyCustomer);
                accountInfo.setNewPrice(bigDecimal);
            }
            if (Objects.isNull(accountInfo.getCreateId())) {
                accountInfo.setNewPrice(accountInfo.getPrice());
            }
        }
    }

    @Override
    public void sensitive(GoodsInfo goodsInfo) {

        List<String> sensitive = sensitive();
        for (String vocabulary : sensitive) {

            String gameName = goodsInfo.getTitle();
            if (Objects.nonNull(gameName)) {
                gameName = gameName.replace(vocabulary, "");
                goodsInfo.setTitle(gameName);
            }

            String des = goodsInfo.getDes();
            if (Objects.nonNull(des)) {
                des = des.replace(vocabulary, "");
                goodsInfo.setDes(des);
            }
        }
    }

    @Override
    public HashMap todayDetail() {
        HashMap<Object, Object> map = new HashMap<>();
        goodsInfoMapper.selectDayCount();
        return map;
    }

    private List<String> sensitive() {
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType(LCConstant.sensitive);
        sysDictData.setStatus(Constants.STR_0);
        List<SysDictData> sysDictDataList = sysDictDataMapper.selectDictDataList(sysDictData);
        return sysDictDataList.stream().map(s -> s.getDictValue()).collect(Collectors.toList());
    }


    public void addVideo(String videoUrl, String videoName, Long goodsId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        goodsInfoImgMapper.deleteByGoodsId(goodsId, Constants.STR_2);
        if (!StringUtils.isEmpty(videoUrl)) {
            GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
            goodsInfoImg.setGoodsId(goodsId);
            goodsInfoImg.setImgUrl(videoUrl);
            goodsInfoImg.setCreateId(loginUser.getUserId());
            goodsInfoImg.setFileName(videoName);
            goodsInfoImg.setType(Constants.STR_2);
            goodsInfoImgMapper.insertGoodsInfoImg(goodsInfoImg);
        }
    }

    @Transactional
    public void bathAddImg(List<Map<String, Object>> imgs, Long goodsInfoId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        goodsInfoImgMapper.deleteByGoodsId(goodsInfoId, Constants.STR_1);
        List<String> result = new ArrayList<>();
        List<GoodsInfoImg> goodsInfoImgList = new ArrayList<>();
        for (Map img : imgs) {
            String filePath = MapUtils.getString(img, "url");
            result.add(filePath);
            if (!StringUtils.isEmpty(filePath)) {
                GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
                goodsInfoImg.setGoodsId(goodsInfoId);
                String fileName = MapUtils.getString(img, "name");
                goodsInfoImg.setImgUrl(filePath);
                goodsInfoImg.setCreateId(loginUser.getUserId());
                goodsInfoImg.setFileName(fileName);
                goodsInfoImg.setType(Constants.STR_1);
                goodsInfoImgList.add(goodsInfoImg);
            }
        }
        goodsInfoImgMapper.insertBacthGoodsInfoImg(goodsInfoImgList);
    }

    String pinjie(Object autoF, GameAttrTemplate gameAttrTemplate, StringBuffer sbuffer) {
        if (Objects.nonNull(autoF)) {
            String vlaues = autoF.toString();
            if (StringUtils.isNotEmpty(vlaues)) {
                if (StringUtils.equals(gameAttrTemplate.getFieldType(), "input")) {
                    sbuffer.append(" and " + gameAttrTemplate.getAavName() + " like \'%" + autoF + "%\'");
                } else if (StringUtils.equals(gameAttrTemplate.getFieldType(), "number") || StringUtils.equals(gameAttrTemplate.getFieldType(), "date")) {
                    if (vlaues.contains("===")) {
                        String[] vlas = vlaues.split("===");
                        if (vlas.length == 2) {
                            if (StringUtils.isNotEmpty(vlas[0])) {
                                sbuffer.append(" and " + gameAttrTemplate.getAavName() + " >= " + vlas[0]);
                            }
                            sbuffer.append(" and " + gameAttrTemplate.getAavName() + " <= " + vlas[1]);
                        } else if (vlas.length == 1) {
                            sbuffer.append(" and " + gameAttrTemplate.getAavName() + " >= " + vlas[0]);
                        }
                    } else {
                        sbuffer.append(" and " + gameAttrTemplate.getAavName() + " >= " + vlaues);
                    }
                } else if (StringUtils.equals(gameAttrTemplate.getFieldType(), "radio")) {
                    sbuffer.append(" and " + gameAttrTemplate.getAavName() + " = " + vlaues);
                } else if (StringUtils.equals(gameAttrTemplate.getFieldType(), "checkbox") || StringUtils.equals(gameAttrTemplate.getFieldType(), "boxradio")) {
                    if (vlaues.contains(",")) {
                        String[] vlas = vlaues.split(",");
                        for (String vla : vlas) {
                            sbuffer.append(" and FIND_IN_SET(\"" + vla + "\"," + gameAttrTemplate.getAavName() + ") >" +
                                    " 0 ");
                        }
                    } else {
                        sbuffer.append(" and FIND_IN_SET(\"" + vlaues + "\"," + gameAttrTemplate.getAavName() + ") >" +
                                " 0 ");
                    }
                }
            }
        }
        return sbuffer.toString();
    }

    String getAllField(GoodsInfo goodsInfo, AccountAttrValue accountAttrValue) {
        Field[] fields = accountAttrValue.getClass().getDeclaredFields();
        Map map1 = new HashMap();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                if (field.getName().startsWith("f")) {
                    map1.put(field.getName(), field.get(accountAttrValue));
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        List<GameAttrTemplate> gameAttrTemplates =
                gameAttrTemplateService.selectGameAttrTemplateByGameId(goodsInfo.getGameId());
        StringBuffer sbuffer = new StringBuffer();
        if (CollectionUtils.isNotEmpty(gameAttrTemplates)) {
            for (GameAttrTemplate gameAttrTemplate : gameAttrTemplates) {
                Object aa = map1.get(gameAttrTemplate.getAavName());
                getGameAttrIds(aa, gameAttrTemplate, sbuffer);
            }
        }
        String gameAttrIds = sbuffer.toString();
        List<GameAttribute> gameAttributes =
                gameAttributeMapper.selectGameAttributeListByIds((Long[]) ConvertUtils.convert(gameAttrIds.split(","),
                        Long.class));
        StringBuffer sbufferV = new StringBuffer();
        for (GameAttribute gameAttribute : gameAttributes) {
            if (sbufferV != null && sbufferV.length() > 0) {
                sbufferV.append("," + gameAttribute.getFieldName());
            } else {
                sbufferV.append(gameAttribute.getFieldName());
            }
        }
        StringBuffer sbufferR = new StringBuffer();
        sbufferR.append(replaceSimpleName(goodsInfo.toString(), goodsInfo.getClass()));
        sbufferR.append(",");
        sbufferR.append(replaceSimpleName(accountAttrValue.toString(), accountAttrValue.getClass()));
        if (sbufferV != null && sbufferV.length() > 0) {
            sbufferR.append(",");
            sbufferR.append(sbufferV.toString());
        }
        return sbufferR.toString();
    }

    String getGameAttrIds(Object autoF, GameAttrTemplate gameAttrTemplate, StringBuffer sbuffer) {
        if (Objects.nonNull(autoF)) {
            String vlaues = autoF.toString();
            if (StringUtils.isNotEmpty(vlaues)) {
                if (StringUtils.equals(gameAttrTemplate.getFieldType(), "radio") || StringUtils.equals(gameAttrTemplate.getFieldType(), "checkbox") || StringUtils.equals(gameAttrTemplate.getFieldType(), "boxradio")) {
                    if (sbuffer != null && sbuffer.length() > 0) {
                        sbuffer.append("," + vlaues);
                    } else {
                        sbuffer.append(vlaues);
                    }
                }
            }
        }
        return sbuffer.toString();
    }

    String replaceSimpleName(String str, Class cla) {
        str = str.replace(cla.getSimpleName() + "(", "")
                .replace("null,", "")
                .replaceAll("\\s*", "")
                .replace(",null", "");
        str = str.substring(0, str.length() - 1);
        return str;
    }

    private static Pattern humpPattern = Pattern.compile("[A-Z]");

    private String humpToLine(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString().toUpperCase();
    }

    public static void main(String[] args) {
        GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto = new GoodsInfoAndAttrValueDto();
//        goodsInfoAndAttrValueDto.setF1("1");
//        goodsInfoAndAttrValueDto.setF2("2");
//        goodsInfoAndAttrValueDto.setF3("3");
//        goodsInfoAndAttrValueDto.setF4("4");
//        goodsInfoAndAttrValueDto.setServerId(1l);
//        goodsInfoAndAttrValueDto.setServerName("哈哈");
//        goodsInfoAndAttrValueDto.setGameId(123l);
//        goodsInfoAndAttrValueDto.setGameName("游戏名字");
//
        GoodsInfo goodsInfo = new GoodsInfo();
        goodsInfo.setCreateId(965456l);
        goodsInfo.setId(123l);
        BeanUtils.copyBeanProp(goodsInfoAndAttrValueDto, goodsInfo);
        System.out.println(goodsInfoAndAttrValueDto.getCreateId());
        System.out.println(goodsInfoAndAttrValueDto.getId());


//        AccountAttrValue accountAttrValue = new AccountAttrValue();
//        BeanUtils.copyBeanProp(goodsInfo, goodsInfoAndAttrValueDto);
//        BeanUtils.copyBeanProp(accountAttrValue, goodsInfoAndAttrValueDto);
//        System.out.println(goodsInfo.toString());
//        System.out.println(goodsInfo.getClass().getSimpleName());
//        System.out.println(goodsInfo.getClass().getName());
    }

    //操作记录
    private void setOper(Long id, Map<String, Object> params) {
        String operation = MapUtils.getString(params, "operation");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        OperationHistory operationHistory = new OperationHistory();
        operationHistory.setAccountId(id);
        operationHistory.setOperator(loginUser.getUsername());
        operationHistory.setOperatTime(new Date());
        operationHistory.setStatus(operation);
        operationHistory.setReason(String.valueOf(id));
        operationHistoryService.insertOperationHistory(operationHistory);
    }

    //推送财务
    public int pushFinance(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto) {
        Finance finance = new Finance();
        finance.setCreateId(SecurityUtils.getUserId());
        finance.setCreateTime(DateUtils.getNowDate());
        finance.setIotype("1");
        long l = 13;
        finance.setBillType(l);
        if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getZdPrice())) {
            finance.setPrice(new BigDecimal(goodsInfoAndAttrValueDto.getZdPrice()));
        } else {
            finance.setPrice(new BigDecimal("0"));
        }

        finance.setField1(goodsInfoAndAttrValueDto.getAccountNumber());
        finance.setField2(goodsInfoAndAttrValueDto.getField2());
        finance.setField4(String.valueOf(goodsInfoAndAttrValueDto.getId()));
        finance.setField5(goodsInfoAndAttrValueDto.getRecyclerName());
        finance.setField6(goodsInfoAndAttrValueDto.getField6());
        finance.setField7(goodsInfoAndAttrValueDto.getField7());
        finance.setField8(goodsInfoAndAttrValueDto.getField8());
        finance.setField9(goodsInfoAndAttrValueDto.getRecycleTime());
        finance.setField10(goodsInfoAndAttrValueDto.getGameName());
        finance.setAtta(goodsInfoAndAttrValueDto.getAtta());

        finance.setRemark(goodsInfoAndAttrValueDto.getZdRemark());

        SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
        finance.setField3(sysUser.getNickName());
        finance.setRegisteruser(sysUser.getNickName());
        finance.setGameId(goodsInfoAndAttrValueDto.getGameId());
        finance.setGameName(goodsInfoAndAttrValueDto.getGameName());
        return financeMapper.insertFinance(finance);
    }

    //推送财务
    public int pushFinanceSH(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, GoodsInfo goodsInfo) {
        Finance finance = new Finance();
        finance.setCreateId(SecurityUtils.getUserId());
        finance.setCreateTime(DateUtils.getNowDate());
        finance.setIotype("1");
        long l = 16;
        finance.setBillType(l);
        if (StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getZdPrice())) {
            finance.setPrice(new BigDecimal(goodsInfoAndAttrValueDto.getZdPrice()));
        } else {
            finance.setPrice(new BigDecimal("0"));
        }

        finance.setField1(goodsInfo.getAccountNumber());
        finance.setField2(goodsInfo.getGameName());
        finance.setField3(goodsInfoAndAttrValueDto.getField3());
        finance.setField4(String.valueOf(goodsInfo.getId()));
        finance.setField5(goodsInfoAndAttrValueDto.getField5());
        finance.setAtta(goodsInfoAndAttrValueDto.getRetrieveHandleImages());
        finance.setRemark(goodsInfoAndAttrValueDto.getRetrieveDes());

        SysUser sysUser = sysUserMapper.selectUserById(SecurityUtils.getUserId());
        finance.setRegisteruser(sysUser.getNickName());
        finance.setGameId(goodsInfo.getGameId());
        finance.setGameName(goodsInfo.getGameName());
        financeMapper.updateFinanceIsShow(goodsInfo.getId());
        return financeMapper.insertFinance(finance);
    }

    /**
     * 一键转让
     */
    @Override
    @Transactional
    public void transferThePossessionOf(Long transferId, Long fromUserId) {
        Long userId = fromUserId;
        if (Objects.nonNull(transferId) && transferId > 0) {
            SysUser sysUser = sysUserMapper.selectUserById(transferId);
            if (Objects.isNull(sysUser)) {
                throw new GlobalException("未找到指定用户");
            }
            if (StringUtils.equals(sysUser.getDelFlag(), "1")) {
                throw new GlobalException("用户已删除");
            }
        }
        goodsInfoMapper.transferThePossessionOf(transferId, userId);
    }

    @Override
    public List<GoodsInfo> selectPush(GoodReq goodReq) {
        return goodsInfoMapper.selectPush(goodReq);
    }


    @Autowired
    private RedisCache redisCache;

    /**
     * 克隆
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public int clone(Long id) {

        String redisKey = "clone_goods_info_all_" + id;
        if (Objects.nonNull(redisCache.getCacheObject(redisKey))) {
            throw new GlobalException("禁止一个小时内重复克隆");
        } else {
            redisCache.setCacheObject(redisKey, "1", 1, TimeUnit.HOURS);
        }
        GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto = selectGoodsInfoAndAttrValueById(id);
        GoodsInfo goodsInfo = new GoodsInfo();
        AccountAttrValue accountAttrValue = new AccountAttrValue();
        BeanUtils.copyBeanProp(goodsInfo, goodsInfoAndAttrValueDto);
        BeanUtils.copyBeanProp(accountAttrValue, goodsInfoAndAttrValueDto);
        String allFeild = getAllField(goodsInfo, accountAttrValue);
        goodsInfo.setAllField(allFeild);
        goodsInfo.setCreateId(SecurityUtils.getUserId());
        goodsInfo.setSaleState(0);
        goodsInfo.setProblemDes("克隆帐号 原编号" + id);
        insertGoodsInfo(goodsInfo);

        goodsInfoAndAttrValueDto.setId(goodsInfo.getId());
        if (!CollectionUtils.isEmpty(goodsInfoAndAttrValueDto.getUrlArr())) {
            bathAddImg(goodsInfoAndAttrValueDto.getUrlArr(), goodsInfo.getId());
        }
        if (!StringUtils.isNull(goodsInfoAndAttrValueDto.getVideoUrl())) {
            addVideo(goodsInfoAndAttrValueDto.getVideoUrl(), goodsInfoAndAttrValueDto.getVideoName(),
                    goodsInfo.getId());
        }
        accountAttrValue.setAccountInfoId(goodsInfo.getId());
        //保存自定义字段
        accountAttrValueMapper.insertAccountAttrValue(accountAttrValue);
        //设置手机号
        setPhone(goodsInfoAndAttrValueDto);
        //异步推送接口
        excuTaskPoolAdd(goodsInfoAndAttrValueDto);
        pushFinance(goodsInfoAndAttrValueDto);
        return 0;
    }

    /**
     * 根据手机号id 统计游戏
     *
     * @param goodsInfo
     * @return
     */
    @Override
    public List<Map<String, Object>> selectGoodsGameTotal(GoodsInfo goodsInfo) {
        return goodsInfoMapper.selectGoodsGameTotal(goodsInfo);
    }
}
